package com.example.lets;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.github.ksoichiro.android.observablescrollview.ObservableListView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;

public class UserActivityList extends BaseActivity implements ObservableScrollViewCallbacks {

    private String input = "";
    private int type;
    private ObservableListView listView;
    private boolean first = true;
    public PullToRefreshActLayout pullLayout;

    public static boolean hasNew = false;
    public static boolean isTop = true;
    public static boolean isBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        listView = (ObservableListView) UserActivityList.this.findViewById(R.id.search_event_view);
        listView.setScrollViewCallbacks(this);

        Intent in = getIntent();
        String mode = in.getStringExtra("mode");
        input = in.getStringExtra("input");
        if (mode.equals("type"))
            type = 0;
        else if (mode.equals("sponsored"))
            type = 1;
        else if (mode.equals("joined"))
            type = 2;
        //loadActivities(null, 1);

        Toolbar toolbar = (Toolbar) this.findViewById(R.id.search_result_toolbar);
        toolbar.setTitle(getIntent().getStringExtra("title"));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (first)
            pullLayout.autoRefresh();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search_result, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void loadActivities(RefreshActListener listener, int action) {
        if (type == 0)
            searchActiByType(listener, action);
        else if (type == 1)
            searchSponsoredUserActivity(listener, action);
        else
            searchJoinedUserActivity(listener, action);
    }

    private int page = 0;
    private ArrayList<HashMap<String, Object>> listActi = new ArrayList<HashMap<String, Object>>();
    private MyAdapter adapter;
    protected void searchActiByType(final RefreshActListener listener, final int mode) {
        final BmobQuery<UserActivity> ActivityQuery = new BmobQuery<UserActivity>("UserActivity");
        ActivityQuery.setLimit(15);
        if (mode != 1) ActivityQuery.setSkip(page * 15);
        else page = 0;
        ActivityQuery.addWhereEqualTo("type", input);
        ActivityQuery.findObjects(this, new FindListener<UserActivity>() {

            @Override
            public void onError(int arg0, String arg1) {
                Toast.makeText(UserActivityList.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    if (mode == 1)
                        listener.refreshFinish(PullToRefreshActLayout.FAIL);
                    else
                        listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                }
            }

            @Override
            public void onSuccess(List<UserActivity> retAct) {
                page++;
                if (mode == 1) listActi = new ArrayList<HashMap<String, Object>>();

                if (first) {
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {

                            String title = (String) listActi.get(position).get("ItemTitle");
                            String description = (String) listActi.get(position).get("ItemText");
                            String picFileName = (String) listActi.get(position).get("ItemPicFileName");
                            String sponsorId = (String) listActi.get(position).get("sponsorId");
                            String type = (String) listActi.get(position).get("type");
                            String place = (String) listActi.get(position).get("place");
                            String time = (String) listActi.get(position).get("time");
                            String ActiId = (String) listActi.get(position).get("id");
                            String detail = (String) listActi.get(position).get("detail");

                            Intent intent = new Intent(UserActivityList.this, EventActivity.class);
                            intent.putExtra("title", title);
                            intent.putExtra("description", description);
                            intent.putExtra("picFileName", picFileName);
                            intent.putExtra("sponsorId", sponsorId);
                            intent.putExtra("place", place);
                            intent.putExtra("detail", detail);
                            intent.putExtra("time", time);
                            intent.putExtra("type", type);
                            intent.putExtra("id", ActiId);

                            startActivity(intent);
                        }
                    });
                    first = false;
                }

                for (UserActivity activity : retAct) {
                    HashMap<String, Object> mapAct = new HashMap<String, Object>();
                    Double dis = HomeActivity.curLoc.distanceInKilometersTo(activity.getGpsAdd());
                    BigDecimal b = new BigDecimal(dis);
                    Double _dis = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    mapAct.put("distance", _dis.toString());
                    mapAct.put("ItemSponsor", activity.getSponsorName());
                    mapAct.put("ItemPicFileName", activity.getPicFilename());
                    mapAct.put("ItemTitle", activity.getName());
                    mapAct.put("number", activity.getPeopleNumber()); // TODO
                    mapAct.put("sponsorId", activity.getSponsorId());
                    mapAct.put("place", activity.getPlace());
                    mapAct.put("detail", activity.getDetailPlace());
                    mapAct.put("time", activity.getStartTime().getDate());
                    mapAct.put("type", activity.getType());
                    mapAct.put("id", activity.getObjectId());
                    listActi.add(mapAct);
                }
                if (listener == null || mode == 1) {
                    adapter = new MyAdapter(UserActivityList.this, listActi);
                    listView.setAdapter(adapter);
                    if (listener != null) listener.refreshFinish(PullToRefreshActLayout.SUCCEED);
                }
                else {
                    hasNew = retAct.size() != 0;
                    adapter.notifyDataSetChanged();
                    listener.loadFinish(hasNew ? PullToRefreshActLayout.SUCCEED
                            : PullToRefreshActLayout.NOMORE, retAct.size());
                }

                //Toast.makeText(UserActivityList.this, "查询到了活动共:" + retAct.size(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private static int cnt = 0;
    private void searchJoinedUserActivity(final RefreshActListener listener, final int mode) {

        if (first) {
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

                    String title = (String) listActi.get(position).get("ItemTitle");
                    String description = (String) listActi.get(position).get("ItemText");
                    String picFileName = (String) listActi.get(position).get("ItemPicFileName");
                    String sponsorId = (String) listActi.get(position).get("sponsorId");
                    String type = (String) listActi.get(position).get("type");
                    String place = (String) listActi.get(position).get("place");
                    String time = (String) listActi.get(position).get("time");
                    String ActiId = (String) listActi.get(position).get("id");
                    String detail = (String) listActi.get(position).get("detail");

                    Intent intent = new Intent(UserActivityList.this, EventActivity.class);
                    intent.putExtra("title", title);
                    intent.putExtra("description", description);
                    intent.putExtra("picFileName", picFileName);
                    intent.putExtra("sponsorId", sponsorId);
                    intent.putExtra("place", place);
                    intent.putExtra("time", time);
                    intent.putExtra("type", type);
                    intent.putExtra("id", ActiId);
                    intent.putExtra("detail", detail);

                    startActivity(intent);
                }

            });
            first = false;
        }

        BmobQuery<Involvement> joinedInvoQuery = new BmobQuery<Involvement>("Involvement");
        joinedInvoQuery.addWhereEqualTo("userId", input);
        joinedInvoQuery.setLimit(15);
        if (mode != 1) joinedInvoQuery.setSkip(page * 15);
        else page = 0;
        joinedInvoQuery.findObjects(this, new FindListener<Involvement>() {
            @Override
            public void onSuccess(final List<Involvement> joinedUserActivityResult) {
                // TODO Auto-generated method stub
                page++;

                if (mode == 1) listActi = new ArrayList<HashMap<String, Object>>();
                if (joinedUserActivityResult.size() == 0) {
                    if (listener == null || mode == 1) {
                        adapter = new MyAdapter(UserActivityList.this, listActi);
                        listView.setAdapter(adapter);
                        if (listener != null)
                            listener.refreshFinish(PullToRefreshActLayout.SUCCEED);
                    } else {
                        hasNew = false;
                        adapter.notifyDataSetChanged();
                        listener.loadFinish(hasNew ? PullToRefreshActLayout.SUCCEED
                                : PullToRefreshActLayout.NOMORE, joinedUserActivityResult.size());
                    }
                    cnt = 0;
                }
                for (Involvement invo : joinedUserActivityResult) {
                    String actId = invo.getActivityId();
                    BmobQuery<UserActivity> joinedUserActivityQuery = new BmobQuery<UserActivity>("UserActivity");
                    joinedUserActivityQuery.getObject(UserActivityList.this, actId, new GetListener<UserActivity>() {

                        @Override
                        public void onSuccess(UserActivity activity) {
                            cnt++;
                            HashMap<String, Object> mapAct = new HashMap<String, Object>();

                            Double dis = HomeActivity.curLoc.distanceInKilometersTo(activity.getGpsAdd());
                            BigDecimal b = new BigDecimal(dis);
                            Double _dis = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                            mapAct.put("distance", _dis.toString());
                            mapAct.put("ItemSponsor", activity.getSponsorName());
                            mapAct.put("ItemPicFileName", activity.getPicFilename());
                            mapAct.put("ItemTitle", activity.getName());
                            mapAct.put("number", activity.getPeopleNumber()); // TODO
                            mapAct.put("sponsorId", activity.getSponsorId());
                            mapAct.put("place", activity.getPlace());
                            mapAct.put("detail", activity.getDetailPlace());
                            mapAct.put("time", activity.getStartTime().getDate());
                            mapAct.put("type", activity.getType());
                            mapAct.put("id", activity.getObjectId());
                            listActi.add(mapAct);

                            if (cnt == joinedUserActivityResult.size()) {
                                if (listener == null || mode == 1) {
                                    adapter = new MyAdapter(UserActivityList.this, listActi);
                                    listView.setAdapter(adapter);
                                    if (listener != null)
                                        listener.refreshFinish(PullToRefreshActLayout.SUCCEED);
                                } else {
                                    hasNew = joinedUserActivityResult.size() != 0;
                                    adapter.notifyDataSetChanged();
                                    listener.loadFinish(hasNew ? PullToRefreshActLayout.SUCCEED
                                            : PullToRefreshActLayout.NOMORE, joinedUserActivityResult.size());
                                }
                                cnt = 0;
                            }
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(UserActivityList.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                            if (listener != null) {
                                if (mode == 1)
                                    listener.refreshFinish(PullToRefreshActLayout.FAIL);
                                else
                                    listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(int arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(UserActivityList.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    if (mode == 1)
                        listener.refreshFinish(PullToRefreshActLayout.FAIL);
                    else
                        listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                }
            }
        });
    }

    private void searchSponsoredUserActivity(final RefreshActListener listener, final int mode) {
        BmobQuery<UserActivity> sponsoredUserActivityQuery = new BmobQuery<UserActivity>("UserActivity");
        sponsoredUserActivityQuery.addWhereEqualTo("sponsorId", input);
        sponsoredUserActivityQuery.setLimit(15);
        if (mode != 1) sponsoredUserActivityQuery.setSkip(page * 15);
        else page = 0;
        sponsoredUserActivityQuery.findObjects(this, new FindListener<UserActivity>() {
            @Override
            public void onSuccess(List<UserActivity> retAct) {
                // TODO Auto-generated method stub
                Log.i("find", "????????????????");
                page++;
                if (mode == 1) listActi = new ArrayList<HashMap<String, Object>>();

                if (first) {
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {

                            String title = (String) listActi.get(position).get("ItemTitle");
                            String description = (String) listActi.get(position).get("ItemText");
                            String picFileName = (String) listActi.get(position).get("ItemPicFileName");
                            String sponsorId = (String) listActi.get(position).get("sponsorId");
                            String type = (String) listActi.get(position).get("type");
                            String place = (String) listActi.get(position).get("place");
                            String time = (String) listActi.get(position).get("time");
                            String ActiId = (String) listActi.get(position).get("id");
                            String detail = (String) listActi.get(position).get("detail");

                            Intent intent = new Intent(UserActivityList.this, EventActivity.class);
                            intent.putExtra("title", title);
                            intent.putExtra("description", description);
                            intent.putExtra("picFileName", picFileName);
                            intent.putExtra("sponsorId", sponsorId);
                            intent.putExtra("place", place);
                            intent.putExtra("time", time);
                            intent.putExtra("type", type);
                            intent.putExtra("id", ActiId);
                            intent.putExtra("detail", detail);

                            startActivity(intent);
                        }

                    });
                    first = false;
                }

                for (UserActivity activity : retAct) {
                    HashMap<String, Object> mapAct = new HashMap<String, Object>();
                    Double dis = HomeActivity.curLoc.distanceInKilometersTo(activity.getGpsAdd());
                    BigDecimal b = new BigDecimal(dis);
                    Double _dis = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    mapAct.put("distance", _dis.toString());
                    mapAct.put("ItemSponsor", activity.getSponsorName());
                    mapAct.put("ItemPicFileName", activity.getPicFilename());
                    mapAct.put("ItemTitle", activity.getName());
                    mapAct.put("number", activity.getPeopleNumber()); // TODO
                    mapAct.put("sponsorId", activity.getSponsorId());
                    mapAct.put("place", activity.getPlace());
                    mapAct.put("detail", activity.getDetailPlace());
                    mapAct.put("time", activity.getStartTime().getDate());
                    mapAct.put("type", activity.getType());
                    mapAct.put("id", activity.getObjectId());
                    listActi.add(mapAct);
                }
                if (listener == null || mode == 1) {
                    adapter = new MyAdapter(UserActivityList.this, listActi);
                    listView.setAdapter(adapter);
                    if (listener != null) listener.refreshFinish(PullToRefreshActLayout.SUCCEED);
                }
                else {
                    hasNew = retAct.size() != 0;
                    adapter.notifyDataSetChanged();
                    listener.loadFinish(hasNew ? PullToRefreshActLayout.SUCCEED
                            : PullToRefreshActLayout.NOMORE, retAct.size());
                }
                //Toast.makeText(UserActivityList.this, "查询到了活动共:" + retAct.size() + "个", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int arg0, String arg1) {
                Toast.makeText(UserActivityList.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
                if (listener != null) {
                    if (mode == 1)
                        listener.refreshFinish(PullToRefreshActLayout.FAIL);
                    else
                        listener.loadFinish(PullToRefreshActLayout.FAIL, 0);
                }
            }
        });
    }

    public boolean ifReachBottom() {
        if (listView.getLastVisiblePosition() == listView.getCount() - 1) {
            int lastIndex = listView.getLastVisiblePosition() - listView.getFirstVisiblePosition();
            View lastItem = listView.getChildAt(lastIndex);
            int height = lastItem.getMeasuredHeight();
            int location[] = new int[2];
            lastItem.getLocationInWindow(location);
            int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
            isBottom = location[1] <= screenHeight - height;
        } else isBottom = false;
        return isBottom;
    }

    @Override
    public void onBackPressed() {
        finish();
        return;
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        Log.i("ui", "scrollY = " + scrollY);
        isTop = scrollY == 0;
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }
}

